package com.example.beryl;
import androidx.activity.result.ActivityResultLauncher;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import com.example.beryl.Util.HandlePublic;
import com.example.beryl.Util.UpdateManager;
import com.example.beryl.UtilActivity.MainActivity;
import com.example.beryl.entity.Action;
import com.example.beryl.entity.Customer;
import com.example.beryl.http.Net_userData;
import com.google.gson.Gson;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.kingdee.bos.webapi.sdk.QueryParam;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 欢迎页面
 */
public class WelecomePage extends AppCompatActivity {
    private Net_userData dbUtil;
    private TextView textView;
    private TextView textView1;
    private Button button;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    HandlePublic handlePublic = new HandlePublic();
    private static final int checkNetwork = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);//取消title
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置页面全屏
        setContentView(R.layout.activity_welecome_page);

        textView = (TextView) findViewById(R.id.log);
        textView1 = (TextView) findViewById(R.id.log1);
        button = (Button) findViewById(R.id.enter);
        dbUtil = new Net_userData();
        final int REQUEST_EXTERNAL_STORAGE = 1;
        if (ContextCompat.checkSelfPermission(WelecomePage.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(WelecomePage.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
            ActivityCompat.requestPermissions(WelecomePage.this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, 101);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        textView.setText("正在为你连接服务器并检查更新");



        String name = getGateway();
        //String ip = getWiFiIPAddress(WelecomePage.this);

        if (name.equals("0.0.0.0")) {
            handlePublic.Alert("请连接网络", WelecomePage.this);
        } else {
            //Action.GateWayIP = name;
            try {
                HandlePublic.inseryt(name,Action.IpGateWay,Action.IpGateWay);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            //handlePublic.startLoad(this);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    CheckConnect();
                }
            }).start();
        }

        handlePublic.setGetResult(new HandlePublic.getResult() {
            @Override
            public void getCode(int what, Object t) throws JSONException {
                getHandle(what, t);
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name1 = getGateway();
                if (name1.equals("0.0.0.0")) {
                    handlePublic.Alert("请连接网络", WelecomePage.this);
                } else {
                    //Action.GateWayIP = name1;
                    try {
                        HandlePublic.inseryt(name1,Action.IpGateWay,Action.IpGateWay);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                   // handlePublic.startLoad(WelecomePage.this);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            CheckConnect();
                        }
                    }).start();
                }
            }
        });
        //加载金蝶账号密码
//        Properties properties = new Properties();
//        AppCfg cfg = null;
//        AppCfg scfg = new AppCfg();
//        InputStream inputStream = null;
//        AssetManager assetManager = this.getApplicationContext().getAssets();
//        try {
//            inputStream = assetManager.open("kdwebapi.properties");
//            properties.load(new InputStreamReader(inputStream, "utf-8"));
//            inputStream.close();
//
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        boolean isLoad = true;
//        if (isLoad) {
//
//            String svr = properties.getProperty("X-KDApi-ServerUrl");
//            if (svr != null) {
//                scfg.setServerUrl(svr);
//            }
//
//            scfg.setdCID(properties.getProperty("X-KDApi-AcctID"));
//            scfg.setUserName(properties.getProperty("X-KDApi-UserName"));
//            scfg.setAppId(properties.getProperty("X-KDApi-AppID"));
//            scfg.setAppSecret(properties.getProperty("X-KDApi-AppSec"));
//            String lcid = properties.getProperty("X-KDApi-LCID");
//            if (lcid != null) {
//                scfg.setlCID(new Integer(lcid));
//            }
//            scfg.setOrgNum(properties.getProperty("X-KDApi-OrgNum"));
//            String timeout = properties.getProperty("X-KDApi-ConnectTimeout");
//            if (timeout != null) {
//                scfg.setConnectTimeout(new Integer(timeout));
//            }
//
//            timeout = properties.getProperty("X-KDApi-RequestTimeout");
//            if (timeout != null) {
//                scfg.setRequestTimeout(new Integer(timeout));
//            }
//
//            timeout = properties.getProperty("X-KDApi-StockTimeout");
//            if (timeout != null) {
//                scfg.setStockTimeout(new Integer(timeout));
//            }
//
//            scfg.setProxy(properties.getProperty("X-KDApi-Proxy"));
//
//        }
//        cfg = scfg;
//        CfgUtil.instance =cfg;


    }

    private void getHandle(int what, Object t) {
        try {
            String ret = handlePublic.dealDataBase((List) t);
            if (ret.contains("[") || ret.contains("{")) {
                switch (what) {
                    case checkNetwork:
                        String version = getAppVersionName(WelecomePage.this);
                        JSONArray jsonArray = new JSONArray(ret);
                        String VersionNet = jsonArray.getJSONObject(0).get("versionName").toString();
                        if (Float.parseFloat(VersionNet) > Float.parseFloat(version)) {
                            UpdateManager manager = new UpdateManager(WelecomePage.this);
                            manager.checkUpdateInfo();
                        } else {
                            Thread.sleep(3000);
                            Intent intent = new Intent();
                            intent.setClass(WelecomePage.this, MainActivity.class);
                            startActivity(intent);
                        }
                        break;
                }
            } else {
                handlePublic.Alert(ret, this);
            }
        } catch (Exception e) {
            handlePublic.Alert(e.getMessage(), this);
        }

    }

    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    private String getAppVersionName(Context context) {
        String versionName = "";

        try {
            PackageManager packageManager = context.getPackageManager();

            PackageInfo packageInfo = packageManager.getPackageInfo("com.example.beryl", 0);

            versionName = packageInfo.versionName;

            if (TextUtils.isEmpty(versionName)) {
                return "";

            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return versionName;
    }

    private void CheckConnect() {
        try {
            List list = new ArrayList();
            list = dbUtil.CheckNetWork();
            handlePublic.setmHandler(checkNetwork, list);
        } catch (Exception e) {
            handlePublic.Alert(e.getMessage(), this);
        }
    }


    public void testQueryCustomer() {
        K3CloudApi api = new K3CloudApi();
        List<Customer> datas = null;
        try {
            datas = api.executeBillQuery(
                    new QueryParam().setFormId("BD_Customer").setFieldKeys("FCUSTID,FNumber,FName,FCreateDate"),
                    Customer.class);
            if (datas != null) {
                Customer meta = ((Customer) (datas.toArray()[0]));
                System.out.println(String.format("%s", new Gson().toJson(meta)));
            } else {
                //fail("datas is null!");
            }
        } catch (Exception e) {

            //fail(e.getMessage());
        }

        if (datas != null) {
            System.out.println(String.format("Total:%s", datas.size()));
        } else {
            //fail("dcs is null!");
        }
    }

    //隐藏按钮
    private void hideButton(boolean result) {
//        if (result) {
//            btn1.setVisibility(View.GONE);
//            btn2.setVisibility(View.GONE);
//            btn3.setVisibility(View.GONE);
//        } else {
//            btn1.setVisibility(View.VISIBLE);
//            btn2.setVisibility(View.VISIBLE);
//            btn3.setVisibility(View.VISIBLE);
//        }
    }


    String getGateway() {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        DhcpInfo dhcp = wifiManager.getDhcpInfo();
        int i = dhcp.gateway;
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF);
    }
}